<?php

namespace app\admin\controller;

use think\Request;
use think\Db;

class Cate extends Common 
{	
	/**
	 * 分类管理主页
	 */
	public function index()
	{	
		$page      = input('?get.page') ? input('get.page') : 1;
		$pageSize  = 2;
		$totalRows = DB::name('cate')->count();
		$totalPage = ceil($totalRows/$pageSize);
		$infoList  = DB::name('cate')->field('id, cName')->order('id')->page($page, $pageSize)->select();

		$this->assign('page', $page);
		$this->assign('infoList', $infoList);		
		$this->assign('pageSize', $pageSize);
		$this->assign('totalPage', $totalPage);

		return $this->fetch();

	}

	/**
	 * 添加分类
	 */
	public function add()
	{	
		if (Request::instance()->isPost()) {
			$cName = input('post.cName');
			$check = DB::name('cate')->where('cName', $cName)->find();
			if ($check) {
				return $this->error('分类已经存在');
			}
			$data['cName'] = $cName;
	  		$id = Db::name('cate')->insertGetId($data);
	  		if($id) {
	  			return $this->success('操作成功','/admin/cate/index');
	  		} else {
	  			return $this->error('操作失败');
	  		}		
		} else {
			return $this->fetch();
		}
		
	}

	/**
	 * 删除分类
	 */
	public function delete()
	{
		$id = input('get.id');
		$num = DB::name('cate')->where('id', $id)->delete();
		if ($num) {
			return $this->success('删除成功', '/admin/cate/index');
		}else{
			return $this->error('删除失败');
		}
	}

	/**
	 * 编辑分类
	 */
	public function edit()
	{
		if (Request::instance()->isPost()) {
			$id   = input('get.id');
			$data = array();
			$cName = input('post.cName');
			if (!$cName) {
				return $this->error('分类不能为空');
			}
			if (DB::name('cate')->where('cName', $cName)->find()) {
				return $this->error('分类已经存在');
			}
			$data['cName'] = $cName;
			$num = DB::name('cate')->where('id', $id)->update($data);
			if ($num) {
				return $this->success('更新成功', '/admin/cate/index');
			}else{
				return $this->error('更新失败');
			}
		}else{
			$id = input('get.id');
			$info = DB::name('cate')->field('cName')->where('id', $id)->find();
			$this->assign('id', $id);
			$this->assign('info', $info);
			return $this->fetch();
		}
	}
}
